import 'dart:math';

import 'package:flutter/material.dart';

import 'handle_view.dart';

class HandleWidget extends StatefulWidget {
  final double zoneR;
  final double handleR;
  final Function(double, double) onHandleListener;
  HandleWidget({this.zoneR = 60.0, this.handleR = 30.0, this.onHandleListener});

  @override
  _HandleWidgetState createState() => _HandleWidgetState();
}

class _HandleWidgetState extends State<HandleWidget> {
  double zoneR;
  double handleR;
  double centerX = 0.0;
  double centerY = 0.0;

  @override
  void initState() {
    zoneR = widget.zoneR;
    handleR = widget.handleR;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanEnd: (d) => reset(),
      onPanUpdate: (d) => parser(d.localPosition),
      child: Container(
        width: 180,
        height: 160,
        child: CustomPaint(
          painter: HandleView(
              zoneR: zoneR,
              handleR: handleR,
              centerX: centerX,
              centerY: centerY),
        ),
      ),
    );
  }

  reset() {
    setState(() {
      centerX = 0;
      centerY = 0;
    });
  }

  parser(Offset offset) {
    setState(() {
      centerX = offset.dx - maxR;
      centerY = offset.dy - maxR;
      var rad = atan2(centerX, centerY);
      if (centerX < 0) {
        rad += 2 * pi;
      }
      var thta = rad - pi / 2; //旋转坐标系90度
      if (sqrt(centerX * centerX + centerY * centerY) > zoneR) {
        centerX = zoneR * cos(thta);
        centerY = -zoneR * sin(thta);
      }
      var len = sqrt(centerX * centerX + centerY * centerY);
      if (widget.onHandleListener != null)
        widget.onHandleListener(rad, len / zoneR);
    });
  }

  double get maxR => zoneR + handleR;
}
